import shortid from 'shortid'
// const lowdb = require('../lowdb/lowdb')
import lowdb from '../lowdb/lowdb'
const dateutil = require('../util/util')
// 查询列表
function queryList () {
  return lowdb.get('projects').value()
}

// 添加项目
function addItem (item) {
  // console.log(item)
  // console.log(shortid.generate())
  // console.log(lowdb)
  lowdb.get('projects').push({
    id: shortid.generate(),
    name: item.name,
    date: dateutil.dateFormat('YYYY-mm-dd HH:MM:SS', new Date()),
    children: [],
    desc: item.desc
  }).write()
}

// 添加标签
function addTag (item) {
  let childrens = lowdb.get('projects').find({ name: item.name }).value().children
  childrens.push({ label: item.tag })
  lowdb.get('projects').find({ name: item.name }).assign({
    children: childrens
  }).write()
}

/**
 * 修改标签
 * @param {表单} item
 * @param {源标签名} before
 */
function updateTag (item, before) {
  let childrens = lowdb.get('projects').find({ name: item.name }).value().children
  childrens.forEach((e, index) => {
    if (e.label === before) { // 删除源标签
      childrens.splice(index, 1)
    }
  })
  childrens.push({ label: item.tag }) // 添加新标签
  lowdb.get('projects').find({ name: item.name }).assign({
    children: childrens
  }).write()
  // 更新资源目录
  lowdb.get('resources').find({name: item.name, tag: before}).assign({
    tag: item.tag
  }).write()
}

// 删除标签
function delTag (item) {
  let childrens = lowdb.get('projects').find({ name: item.name }).value().children
  childrens.forEach((e, index) => {
    if (e.label === item.tag) {
      childrens.splice(index, 1)
    }
  })
  lowdb.get('projects').find({ name: item.name }).assign({
    children: childrens
  }).write()
}

// 修改项目
function updateItem (item) {
  lowdb.get('projects').find({ id: item.id }).assign({ name: item.name, desc: item.desc }).write()
}

// 删除项目
function delItem (item) {
  lowdb.get('projects').remove({ id: item.id }).write()
}

export { queryList, addItem, updateItem, delItem, addTag, updateTag, delTag }
